package com.kongming.kmdm.ws.guice;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.Stage;

public class WSGuice {

    public static Injector injector = null;

    private static final Lock lock = new ReentrantLock ();

    private static Injector init (List <Module> modules) {

        if (injector == null) {
            try {
                lock.lock ();
                if (injector == null) {
                    injector = Guice.createInjector (Stage.DEVELOPMENT, modules);
                }
            }
            finally {
                lock.unlock ();
            }
        }
        return injector;
    }

    public static <T> T getInstance (Class <T> clazz) {

        if (injector != null) {
            return injector.getInstance (clazz);
        }
        else {
            List <Module> modules = new ArrayList <Module> ();
            return WSGuice.init (modules).getInstance (clazz);
        }
    }

    public static void initActor (List <Module> modules) {

        if (injector == null) {
            init (modules);
        }
    }
}
